using System;
using Godot;
using Godot.Collections;
using PlayerWeapon;

namespace PlayerState
{
partial class Attack : Node,StateNode
{    
    public Player player;

    public Timer cdTimer;

    public Weapon weapon;
    //the use
    public AnimatedSprite2D current;

    public override void _Ready()
    {
        player = GetNode<Player>("/root/Main/Player");
        cdTimer = GetNode<Timer>("CD");
                
        weapon = player.GetNode<Weapon>("Weapon");
        
        cdTimer.Timeout+=OnCDTimeout;
    }

    public void OnAttack()
    {           
        Vector2 mousePosition = player.GetGlobalMousePosition();
        float angle = Mathf.Atan2(mousePosition.Y - player.Position.Y, mousePosition.X - player.Position.X);//[-Mathf.Pi,Mathf.Pi]
        if (angle >= -Mathf.Pi / 4 && angle <= Mathf.Pi / 4)
        {
            current = weapon.right;
            player.FacingLeft=false;
        }
        else if (angle >= Mathf.Pi / 4 && angle <= 3 * Mathf.Pi / 4)
            current = weapon.down;
        else if (angle >= 3 * Mathf.Pi / 4 && angle <= Mathf.Pi || angle >= -Mathf.Pi && angle <= -3 * Mathf.Pi / 4)
        {
            current = weapon.left;
            player.FacingLeft=true;
        }
        else
            current = weapon.up;
                
        weapon.OnAttack(current);
    }

    public void OnCDTimeout()
    {
        player.IsAttack = false;
        player.CanRoll = true;

        if(!player.IsOnFloor())
            player.SwitchTo("Fall");
        if(player.IsRun())
            player.SwitchTo("Run"); 
        else
            player.SwitchTo("Idle");
    }

    public void OnEnter()
    {                
        player.IsAttack = true;
        player.CanRoll = false;
        player.GetNode<AnimatedSprite2D>("AnimaPlayer").Animation="attack";
             
        OnAttack();        
        cdTimer.Start();
    }

    public void OnExit()
    {        
    }

    public void OnUpdate(float delta)
    {
        if(player.Health<=0)
            player.SwitchTo("dead");   
    }

}
}